package com.pes.arcww.controller;

import javax.servlet.http.HttpServletRequest;
import net.sf.uadetector.ReadableUserAgent;
import net.sf.uadetector.UserAgentStringParser;
import net.sf.uadetector.service.UADetectorServiceFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;

import com.pes.arcww.service.UsersService;

@Controller
public class UtilsApp {
	
	private static final Logger logger = LoggerFactory
		       .getLogger(UtilsApp.class);

	public ModelMap init(HttpServletRequest request, ModelMap model, UsersService userService) {
		
		//get device channel
		model = this.getAUDetect(request, model);
		//get user if is logged in current session
		model = this.getLogged(request, model, userService);
		
		return model;
	}
	/**
	 * Detect device channel
	 * 
	 * @param request
	 * @param model
	 * @return model
	 */
	public ModelMap getAUDetect(HttpServletRequest request, ModelMap model){
		
		logger.info("Device detection");
		UserAgentStringParser parser = UADetectorServiceFactory.getResourceModuleParser();
		ReadableUserAgent agent = parser.parse(request.getHeader("User-Agent"));
		model.addAttribute("m_dev", agent.getDeviceCategory());
		
		return model;
	}
	
	public ModelMap getLogged(HttpServletRequest request, ModelMap model, UsersService userService){
		if(request.getSession().getAttribute("logged_user") != null){
			model.addAttribute("m_user", userService.getUser((String) request.getSession().getAttribute("logged_user")));
		}
		
		return model;
	}
	
}
